//
//  WBRefreshControl.swift
//  Weibo
//
//  Created by xu on 2017/3/27.
//  Copyright © 2017年 xuantong. All rights reserved.
//

import UIKit

//枚举,label的文字改变

private let refreshControlH: CGFloat = 50

enum RefreshControlState:String {
    
    case normal = "正常中"
    case pulling = "下拉中"
    case refreshing = "刷新中"
    
}



class WBRefreshControl: UIControl {
    
    //记录控件
    var scrollView : UIScrollView?
    
    var myState: RefreshControlState = .normal {
        
        didSet{
            messageLabel.text = myState .rawValue
            
            switch myState {
            case .normal:
                
                //如果是刷新中
                if oldValue == .refreshing{
                  
                    UIView.animate(withDuration: 0.25, animations: {
                       
                        self.scrollView?.contentInset.top -= refreshControlH
                         self.indicatorView.stopAnimating()
                        
                    }, completion: { (_) in
                        
                        self.refreshImageView.isHidden = false
//                        self.indicatorView.stopAnimating()
                    })
       
                    // 设置动画 --恢复位置
                    UIView.animate(withDuration: 0.25, animations: {
                        self.refreshImageView.transform = CGAffineTransform.identity
                    })

                }
            //下拉 - 图片旋转
            case .pulling:
                
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.refreshImageView.transform = CGAffineTransform(rotationAngle: CGFloat(-3 * M_PI))
                })
                
                
            case.refreshing :
             
            UIView.animate(withDuration: 0.25, animations: {
                    //加高50
                    self.scrollView?.contentInset.top += refreshControlH
                    //隐藏箭头
                    self.refreshImageView.isHidden = true
                    //开始执行圈圈
                    self.indicatorView.startAnimating()
                    
                }, completion: { (_) in
                    // 发送
                    self.sendActions(for: UIControlEvents.valueChanged)
                })
            }
        }
    }
    //重写父类构造方法
    override init(frame: CGRect) {
        
        super.init(frame: CGRect(x:0, y: -refreshControlH, width: UIScreen.main.bounds.width, height: refreshControlH))
        
        self.backgroundColor = UIColor.white
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        
        
        func endRefreshing(){
            myState = .normal
        }
    }
    
    
    
    override func willMove(toSuperview newSuperview: UIView?) {
        guard let view = newSuperview as? UIScrollView else{
            return
        }
        
        scrollView = view
    
        // 使用KVO监听newSuperview属性变化
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.new, context: nil)
        
    }
    
    
    
    //MARK: 供外界调用的方法 结束刷新
    func endRefreshing(){
        // 吧控件的状态改为正常
        myState = .normal
    }

    
    
    // 通过KVO监听方法来监听scrollView 属性变化
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        //取出 .scrollView?.contentOffset.y
        let contentOffsetY = self.scrollView!.contentOffset.y
        let contentOffsetMaxY = -self.scrollView!.contentInset.top - refreshControlH
        
        
        if self.scrollView!.isDragging {
            
            if contentOffsetY < contentOffsetMaxY && myState == .normal {
                print("下拉中")
                
                myState = .pulling
            }else if contentOffsetY >= contentOffsetMaxY && myState == .pulling{
                //正常状态 将赋值为默认
                print("正常中")
                myState = .normal
            }else{
                if myState == .pulling {
                    //则是刷新的状态
                    myState = .refreshing
             }
         }
     }
 }
    
    
    //MARK: 设置视图
    private func setupUI(){
        
        self.backgroundColor = UIColor.orange
        addSubview(messageLabel)
        addSubview(refreshImageView)
        addSubview(indicatorView)
        
        //取消布局
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        //添加约束
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
       
        refreshImageView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: refreshImageView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: refreshImageView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
    
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
        
        
    }
    
    
    //实例化label
    fileprivate lazy var messageLabel:UILabel = {
       
        let lab = UILabel()
        lab.textColor = UIColor.white
        lab.text = "正常中"
        lab.textAlignment = .center
        lab.font = UIFont.systemFont(ofSize: 14)
        return lab
        
    }()
    
    
    //箭头
    private lazy var refreshImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //圈圈
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView()
    
    
    //移除KVO
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }

    
    
}






